package com.example.video.plateRecognition.application.command;

import com.example.video.common.util.XmlUtils;
import com.example.video.plateRecognition.client.dto.LicensePlateAddCmd;
import com.example.video.plateRecognition.infrastructure.manage.VehicleManage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;

@Component
public class LicensePlateAddCmdExe {

    private static final Logger logger = LoggerFactory.getLogger(LicensePlateAddCmdExe.class);

    public static DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    public void execute(LicensePlateAddCmd command) {

        VehicleManage manage = new VehicleManage();

        // 初始化
        manage.initDevice();

        logger.info("开始登录");

        manage.login_V40(command.getIp(),(short) 8000,command.getUsername(),command.getPassword());
        String xmlString = manage.searchVehicleList(command.getPlateNumber(), command.getChannel(), 1);
        logger.info("查询返回报文："+xmlString);
        String numOfMatches = XmlUtils.getValueFromTag(xmlString, "numOfMatches");
        if (Integer.parseInt(numOfMatches) == 0){
            logger.info("查询到车牌号："+command.getPlateNumber()+"不存在，可添加");
            manage.addVehicleList(command.getPlateNumber(),convertToDate(command.getStartTime()),convertToDate(command.getStopTime()));
        }else {
            logger.info("查询到车牌号："+command.getPlateNumber()+"已存在，先删除后添加");
            manage.deleteVehicleList(command.getPlateNumber(),command.getChannel());
            manage.addVehicleList(command.getPlateNumber(),convertToDate(command.getStartTime()),convertToDate(command.getStopTime()));
        }
        logger.info("车牌号："+command.getPlateNumber()+"，添加成功");
        //用户注销，释放SDK
        manage.deviceLogout();
    }


    public LocalDateTime convertToDate(String dateString) throws DateTimeParseException {
        DateTimeFormatter formatterWithTime = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        try {
            return LocalDateTime.parse(dateString, formatterWithTime);
        } catch (DateTimeParseException e1) {
            // 如果第一个格式不匹配，尝试第二个格式
            try {
                return LocalDateTime.parse(dateString+" 00:00:00", formatterWithTime);
            } catch (DateTimeParseException e2) {
                throw new DateTimeParseException(
                        "Input string does not match any of the expected formats: 'yyyy-MM-dd' or 'yyyy-MM-dd HH:mm:ss'",
                        dateString,
                        0
                );
            }
        }
    }
}
